package com.example.demo.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.example.demo.framework.CustomPage;
import com.example.demo.framework.base.BaseService;
import com.example.demo.model.Item;

@Service
public class ItemService extends BaseService {

	@SuppressWarnings("unchecked")
	public CustomPage findItem(int pageNo, int pageSize, Item item, Integer userLevel) {
		CustomPage cPage = new CustomPage();
		String field = "new Map(i.iID as iID, c.name as name,i.title as title,i.itemCode as itemCode,i.price as price,i.itemURL as itemURL,"
				+ "i.imageURL as imageURL,i.brand as brand,i.skuStr as skuStr,i.modifyTime as modifyTime,i.marketTime as marketTime,"
				+ "i.status as status, s.sID as sID, s.storageName as storageName)";
		StringBuilder hql = new StringBuilder(
				"SELECT %s from Item i left join Category c on i.categoryID=c.categoryID left join Storage s on i.sID=s.sID WHERE 1=? ");
		List<Object> values = new ArrayList<>();
		values.add(1);
		if (item.getStatus() != null) {
			hql.append(" and i.status=? ");
			values.add(item.getStatus());
		}
		if (item.getsID() != null) {
			hql.append(" and i.sID=? ");
			values.add(item.getsID());
		}
		if (StringUtils.isNotEmpty(item.getItemID())) {
			hql.append(" and i.itemID=? ");
			values.add(item.getItemID());
		}
		if (StringUtils.isNotEmpty(item.getTitle())) {
			hql.append(" and i.itemID like '%" + item.getTitle() + "%' ");
		}
		if (userLevel != null) {
			hql.append(" and find_in_set('" + userLevel + "', s.filterUserLevel) > 0");
		}
		hql.append(" order by i.iID desc");
		cPage.setContent(createQuery(String.format(hql.toString(), field), values.toArray())
				.setFirstResult(CustomPage.getStartOfPage(pageNo, pageSize)).setMaxResults(pageSize).getResultList());
		cPage.setTotal(
				(long) createQuery(String.format(hql.toString(), SQL_COUNT), values.toArray()).getSingleResult());
		cPage.setPageNo(pageNo + 1);
		cPage.setSize(pageSize);
		return cPage;
	}

}
